<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="referrer" content="never"> 
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../css/utils/bootstrap.min.css" />
    <link rel="stylesheet" href="../../css/utils/common.css?version=2" />
    <link rel="stylesheet" href="../../css/utils/toastr.min.css" />
	<title></title>
	<style>
		.border-input .form-control{
			border: none;
			margin-bottom: 10px;
		}
		.share-span {
			color: #666;
		}
		.upload-img {
			margin-top: 10px;
			width: 70px;
			height: 70px;
			background: url(../../img/myExtension/upload-logo.png) no-repeat;
			background-size: 100% 100%;
		}
		.upload-img input::-webkit-file-upload-button {
            width: 70px;
            height: 70px;
            border: none;
            position: absolute;
            outline: 0;
            opacity: 0;
        }
        .upload-img input[type='file'] {
            display: block;
            width: auto;
            border: 0;
            vertical-align: middle;
        }
        .label-select {
        	width: calc(100% + 20px);
        	padding: 10px;
        	margin-top: 40px;
        	margin-left: -10px;
        	margin-right: -10px;
        	background-color: #f3f3f3;
        }
        .label-select .label-title {
		    margin-bottom: 10px;
		    color: #6F6F6F;
		}
		.label-select .label-group .label {
		    display: inline-block;
		    padding: 3px 20px;
		    margin-right: 15px;
		    margin-bottom: 15px;
		    background-color: #E1E1E1;
		    color: #848484;
		    cursor: pointer;
		    border-top-left-radius: 10px;
		    border-top-right-radius: 10px;
		    border-bottom-left-radius: 10px;
		    border-bottom-right-radius: 10px;
		}
		.label-select .label-group .label.active {
		    background-color: #11B5AB;
		    color: #fff;
		}
		.next-step {
			margin-top: 20px;
		}
		.next-step button.active {
			background-color: #11B5AB;
		    color: #fff;
		    border-color: #11B5AB;
		}
		.border-url-input .prompt {
			margin-top: 20px;
			margin-bottom: 5px;
			color: #666;
		}
		.border-url-input  .form-control{
			border: none;
		}
	</style>
</head>
<body>
	<div class="content">
		<div class="border-input">
			<input type="text" id="title" maxlength="32" class="form-control" onkeyup="checklength(this,32);" placeholder="文章标题（最多32个字）">
			<textarea class="form-control" id="abstracts" maxlength="54" rows="3" onkeyup="checklength(this,54);" placeholder="文章摘要（最多54个字）"></textarea>
		</div>
		<div>
			<div class="share-span">分享预览图</div>
			<div class="upload-img">
				<input type="hidden" id="imageUrl" value="" />
				<input type="file" name="file" id="file" value="" accept="image/*" multiple onchange="handleInputChange();" />
			</div>
		</div>
		<div class="border-url-input">
			<div class="prompt">输入链接地址</div>
			<input type="text" id="contentsLink" maxlength="32" class="form-control" placeholder="请输入正确的链接地址">
		</div>
		<div class="label-select">
			<div class="label-title">
				<label>标签：</label>
			</div>
			<div class="label-group">
				<!--<span class="label label-default active">奶茶</span>-->
			</div>
		</div>
		<div class="next-step">
			<button type="button" id="nextStep" class="btn btn-block" disabled="disabled">下一步</button>
		</div>
	</div>
	<script type="text/javascript" src="../../js/utils/jquery-1.12.4.min.js" ></script>
	<script type="text/javascript" src="../../js/utils/bootstrap.min.js" ></script>
	<script type="text/javascript" src="../../js/utils/toastr.min.js" ></script>
	<script type="text/javascript" src="../../js/utils/jquery.cookie.js" ></script>
	<script type="text/javascript" src="../../js/utils/regular.js?version=1" ></script>
	<script type="text/javascript" src="../../js/utils/boot.js" ></script>
	<script>
		var userID,companyID,articleID;
		var lableIDList;
		$(function(){
			articleID = base.getParameter("articleID");
			userID = $.cookie("userID");
			companyID = $.cookie("companyID");
			toastr.options = {
                "timeOut": 2000,
                "positionClass": "toast-middle-center"
            };
            //获取推文详情
            if (articleID != null && articleID != "") {
            	base.postData(base.url.getArticleInfo, {userID:userID,companyID:companyID,articleID:articleID}, callbackGetArticleInfo);
            }else{
				//获取公司标签
				base.postData(base.url.lableList, {userID:userID,companyID:companyID}, callbackLableList);	
            }
		});
		//推文详情返回
		function callbackGetArticleInfo(data) {
			if (data.success) {
				$("#contentsLink").val(data.context.contentsLink);
				$("#title").val(data.context.articleTitle);
				$("#abstracts").val(data.context.articleAbstracts);
				$("#imageUrl").val(data.context.articleImage);
				$(".upload-img").css("background-image", "url("+data.context.articleImage+")");
				$(".upload-img").css("background-size", "100% 100%");
				checkRule();
				lableIDList = new Array();
				for (var i=0;i<data.context.lableList.length;i++) {
					lableIDList.push(data.context.lableList[i].id);
				}
				//获取公司标签
				base.postData(base.url.lableList, {userID:userID,companyID:companyID}, callbackLableList);
			}
		}
		//公司标签列表返回
		function callbackLableList(data) {
			if (data.success) {
				var html = "";
				for (var i=0; i<data.context.dataList.length; i++) {
					var isActive = false;
					if (lableIDList != null && lableIDList != "") {
						for (var j=0; j<lableIDList.length; j++) {
							if (data.context.dataList[i].id == lableIDList[j]) {
								isActive = true;
								break;
							}
						}
					}
					if (isActive) {
						html += '<span class="label label-default active" data-id="'+data.context.dataList[i].id+'">'+data.context.dataList[i].lableName+'</span>'
					}else{
						html += '<span class="label label-default" data-id="'+data.context.dataList[i].id+'">'+data.context.dataList[i].lableName+'</span>'	
					}
					
				}
				$(".label-select .label-group").html(html);
			}
		}
		//输入框字节长度
		function checklength(obj, number){
			if ($(obj).val().length > number) {
				$(obj).val($(obj).val().substring(0, number));
			}
			checkRule();
		}
		//判断是否填写
		function checkRule() {
			var title = $("#title").val();
			var abstracts = $("#abstracts").val();
			var imageUrl = $("#imageUrl").val();
			var contentsLink = $("#contentsLink").val();
			if (title != null && title != "" && abstracts != null && abstracts != "" && imageUrl != null && imageUrl != "" && isURL(contentsLink)) {
				$('#nextStep').removeAttr('disabled');
				$("#nextStep").addClass("active");
			}else{
				$('#nextStep').attr('disabled','disabled');
				$("#nextStep").removeClass("active");
			}
		}
		//点击下一步
		$("#nextStep").click(function(){
			if ($(this).attr("class").indexOf("active") != -1) {
				var title = $("#title").val();
				var abstracts = $("#abstracts").val();
				var imageUrl = $("#imageUrl").val();
				var contentsLink = $("#contentsLink").val();
				//获取标签
				var lableLength = $(".label-select .label-group").find(".active").length;
				if (lableLength >= 6) {
					toastr.warning("最多选择六个标签！");
					return;
				}
				var lableID = "";
				$(".label-select .label-group").find(".active").each(function(i){
					if ((i+1) == lableLength) {
						lableID += $(this).attr("data-id");
					}else{
						lableID += $(this).attr("data-id") + ",";
					}
				})
				var data = {
					userID:userID,
					companyID:companyID,
					articleID:articleID,
					title:title,
					abstracts:abstracts,
					imageUrl:imageUrl,
					lableID:lableID,
					category:1,
					contentsLink:contentsLink
				}
				data = JSON.stringify(data);
				$.cookie("contentUrlData", data);
				window.parent.location = "../index.html?path=myExtension/createPhoneUrlContent2.html?articleID="+articleID;
			}
		});
		//点击选择标签
		$(".label-select .label-group").on("click", "span", function(){
			//正反选
			if ($(this).attr("class").indexOf("active") != -1) {
				$(this).removeClass("active");
			}else{
				var lableLength = $(this).closest(".label-group").find(".active").length;
				if (lableLength >= 6) {
					toastr.warning("最多选择六个标签！");
					return;
				}
				$(this).addClass("active");
			}
		});
		var fileData;//文件资源
		var imgFile = {};//文件信息
		function handleInputChange(){
			//先判断是否已有五张图片
			fileData = event.target.files[0];
			const imgMasSize = 1024 * 1024 * 5; // 5MB
			// 检查文件类型
		    if(['jpeg', 'png', 'gif', 'jpg'].indexOf(fileData.type.split("/")[1]) < 0){
		        toastr.warning("文件类型仅支持 jpeg/png/gif！");
		        return;
		    }
		    // 文件大小限制
		    if(fileData.size > imgMasSize ) {
		        // 文件大小自定义限制
		        toastr.warning("文件大小不能超过5MB！");
		        return;
		    }
			// 判断是否是ios
		    if(!!window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
		        // iOS
		        uploadFile(fileData);
		    } else {
	    		transformFileToDataUrl(fileData);
		    }
		}
		// 将file转成dataUrl
		function transformFileToDataUrl (file) {
		    const imgCompassMaxSize = 200 * 1024; // 超过 200k 就压缩
		
		    // 存储文件相关信息
		    imgFile.type = file.type || 'image/jpeg'; // 部分安卓出现获取不到type的情况
		    imgFile.size = file.size;
		    imgFile.name = file.name;
		    imgFile.lastModifiedDate = file.lastModifiedDate;
		
		    // 封装好的函数
		    const reader = new FileReader();
		
		    // file转dataUrl是个异步函数，要将代码写在回调里
		    reader.onload = function(e) {
		        const result = e.target.result;
		
		        if(result.length < imgCompassMaxSize) {
		            compress(result, processData, false);    // 图片不压缩
		        } else {
		            compress(result, processData, true);            // 图片压缩
		        }
		    };
		
		    reader.readAsDataURL(file);
		}
		// 使用canvas绘制图片并压缩
		function compress (dataURL, callback, shouldCompress) {
		    const img = new window.Image();
		    img.src = dataURL;
		    img.onload = function () {
		        const canvas = document.createElement('canvas');
		        const ctx = canvas.getContext('2d');
		
		        canvas.width = img.width;
		        canvas.height = img.height;
		
		        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
		
		        var compressedDataUrl;
		
		        if(shouldCompress){
		            compressedDataUrl = canvas.toDataURL(imgFile.type, 0.2);
		        } else {
		            compressedDataUrl = canvas.toDataURL(imgFile.type, 1);
		        }
		        callback(compressedDataUrl);
		    }
		}
		function processData (dataUrl) {
		    // 这里使用二进制方式处理dataUrl
		    const binaryString = window.atob(dataUrl.split(',')[1]);
		    const arrayBuffer = new ArrayBuffer(binaryString.length);
		    const intArray = new Uint8Array(arrayBuffer);
//		    const imgFile = this.imgFile;
		    for (var i = 0, j = binaryString.length; i < j; i++) {
		        intArray[i] = binaryString.charCodeAt(i);
		    }
		    const data = [intArray];
		    var blob;
		    try {
		        blob = new Blob(data, { type: imgFile.type });
		    } catch (error) {
		        window.BlobBuilder = window.BlobBuilder ||
		            window.WebKitBlobBuilder ||
		            window.MozBlobBuilder ||
		            window.MSBlobBuilder;
		        if (error.name === 'TypeError' && window.BlobBuilder){
		            const builder = new BlobBuilder();
		            builder.append(arrayBuffer);
		            blob = builder.getBlob(imgFile.type);
		        } else {
		            toastr.warning("版本过低，不支持图片压缩");
		            throw new Error('版本过低，不支持上传图片');
		        }
		    }
		    // blob 转file
		    const fileOfBlob = new File([blob], imgFile.name);
		    uploadFile(fileOfBlob)
		}
		
		//上传图片
		function uploadFile(imgfile){
			toastr.info("正在上传，请稍等...");
			var formData = new FormData();
			formData.append('Filedata', imgfile);
			formData.append('type', 1);
	//		formData.append('myfile', $('input[name=file]')[0].files[0]);
			$.ajax({
	            url: base.url.uploadFile,
	            method: 'POST',
	            data: formData,
	            contentType: false, // 注意这里应设为false
	            processData: false,
	            cache: false,
	            success: function(data) {
	            	console.log(data.obj);
	            	$("#imageUrl").val(data.obj);
					$(".upload-img").css("background-image", "url("+data.obj+")");
					$(".upload-img").css("background-size", "100% 100%");
					checkRule();
	            },
	            error: function (jqXHR) {
	                console.log(data.obj);
	            }
	        })
		}
	</script>
</body>
</html>
